<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>鹰眼选股</title>
</head>
<body>
<?php
$jsonString = file_get_contents("ret.json");
$data = json_decode($jsonString, true);
$codes = $data["codes"];
$dates = $data["dates"];
$infos = $data["infos"];

function isMobile() {
    if (isset($_SERVER['HTTP_USER_AGENT'])) {
        $user_agent = $_SERVER['HTTP_USER_AGENT'];
        $mobile_agents = Array("Android", "iPhone", "iPod", "iPad", "Windows Phone", "BlackBerry", "SymbianOS");
        foreach ($mobile_agents as $mobile_agent) {
            if (strpos($user_agent, $mobile_agent) !== false) {
                return true;
            }
        }
    }

    return false;
}

function startsWith($haystack, $needle) {
    $length = strlen($needle);
    return (substr($haystack, 0, $length) === $needle);
}

function getStockUrl($code) {
    if (startsWith($code, "60") || startsWith($code, "900")) {
        return "href='http://quote.eastmoney.com/sh" . $code . ".html'";
    } else if (startsWith($code, "688")) {
        return "href='http://quote.eastmoney.com/kcb/" . $code . ".html'";
    } else {
        return "href='http://quote.eastmoney.com/sz" . $code . ".html'";
    }
}

function formatStock($obj, $date) {
    if (stristr($obj["late"], 'UP') !== false) {
        $str = "<p style='color:red; font-size:10px'>";
    } else if (stristr($obj["late"], 'DN') !== false) {
        $str = "<p style='color:green; font-size:10px'>";
    } else {
        $str = "<p style='color:black; font-size:10px'>";
    }
    $str = $str . "日期: " . $date . "<br/>";
    $str = $str . "最低: " . $obj["low"] . "<br/>";
    $str = $str . "最高: " . $obj["high"] . "<br/>";
    $str = $str . "最近: " . $obj["late"] . "<br/>";
    $str = $str . "扭亏: " . $obj["jlr"] . "<br/>";
    $str = $str . "空间: " . $obj["space"] . "<br/>";
    return $str;
}

echo "<div><b>实时资金流排名</b></div>\n";
echo "<table border='1px' cellspacing='0px'>\n";
$flow_tag = array("排名","名称","价格","涨幅","主力","超大单");
$flow_id = array("order","name","price","up","mbig","sbig");
for($i=0;$i<10;$i++) {
    $max_cols = count($flow_tag);
    if ($i == 0) {
        // 表头
        echo "<tr>\n";
        for($j=0;$j<$max_cols;$j++) {
            echo "<th>" . $flow_tag[$j] . "</th>\n";
        }
        echo "</tr>\n";
    }
    echo "<tr>\n";
    for($j=0;$j<$max_cols;$j++) {
        if ($j==0) {
            echo "<td id='rank_" . $i . "_" . $flow_id[$j] . "' style='text-align:center;font-size:10px;'>" . ($i + 1) . "</td>\n";
        } else {
            echo "<td id='rank_" . $i . "_" . $flow_id[$j] . "' style='font-size:10px;'></td>\n";
        }
    }
    echo "</tr>\n";
}
echo "</table>\n";
echo "<br/>\n";


if (!isMobile()) {
    echo "<div><b>近期扭亏为赢公告</b></div>\n";
    echo "<table border='1px' cellspacing='0px'>\n";
    $lrb_json = file_get_contents("lrb-date.json");
    $lrb = json_decode($lrb_json, true);
    $cnt = 0;
    $max_rows = 5;
    $max_cols = 0;
    foreach ($lrb as $date => $list) {
        if ($cnt++ >= $max_rows) {
            break;
        }
        $cols = count($list);
        if ($cols > $max_cols) {
            $max_cols = $cols;
        }
    }
    $cnt = 0;
    foreach ($lrb as $date => $list) {
        if ($cnt++ >= $max_rows) {
            break;
        }
        $cols = count($list);
        if ($cnt % 2 == 0) {
            $bg = " style='background-color: #FFCCE1;'";
        } else {
            $bg = " style='background-color: #FFE4E1;'";
        }

        echo "<tr>\n";
        for($j=0;$j<$max_cols;$j++) {
            if ($j == 0) {
                echo "<td" . $bg . "><b>" . $date . "</b></td>\n";
            }

            if ($j >= $cols) {
                echo "<td" . $bg . "/>";
                continue;
            }

            $item = $list[$j];

            echo "<td" . $bg . ">";
            echo "<a " . getStockUrl($item["code"]) . " target='_blank'>" . $item["name"] . "-" . $item["code"] . "</a>";
            echo "<div style='font-size:10px;'>" . $item["detail"] . "</div>\n";
            echo "</td>";
        }
        echo "</tr>\n";
    }
    echo "</table>\n";
    echo "<br/>\n";
}


echo "<div><b>历史数据筛选</b></div>\n";
echo "<table border='1px' cellspacing='0px'>\n";
$template = "时间: ??<br/>价格: ??<br/>昨收: ??<br/>量比: ??<br/>涨跌幅: ??<br/>成交量: ??<br/>超大单流入: ??<br/>主力净流入: ??";
$max_cols = count($dates);
$max_rows = count($codes);
$history = $data["history"];

if (isMobile()) {
    $start_cols = $max_cols - 3;
} else {
    $start_cols = $max_cols - 8;
}

if ($start_cols < 0) {
    $start_cols = 0;
}

function formatStockInfo($info) {
    if (is_null($info)) {
        return "";
    }

    return "行业:" . $info['cls'] . "  总市值:" . $info['zsz'] . " 流通市值:" . $info['ltsz'];
}


for($i=0;$i<$max_rows;$i++) {
    if ($i == 0) {
        // 表头
        echo "<tr>\n";
        for($j=$start_cols;$j<$max_cols;$j++) {
            echo "<th>" . $dates[$j] . "-共" . count($history[$dates[$j]]) . "只</th>\n";
            if ($j==($max_cols-1)) {
                echo "<th id='realtime'>实时</th>\n";
            }
        }
        echo "</tr>\n";
    }

    $code = $codes[$i];
    $info = $infos[$code];
    $title = "<a " . getStockUrl($code) . " target='_blank'>" . $info["name"] . "-" . $code . "</a>";
    $title = $title . "<div style='font-size:10px;'>" . formatStockInfo($info) . "</div>";
    echo "<tr>\n";
    echo "<td colspan='" . ($max_cols + 1) . "' style='text-align:center;background-color: #FFED97;'>" . $title. "</td>\n";
    echo "</tr>\n";

    echo "<tr>\n";
    for($j=$start_cols;$j<$max_cols;$j++) {
        $date = $dates[$j];

        if (!isset($history[$date][$code])) {
            echo "<td style='text-align:center'>" . $date . "未上榜</td>\n";
            if ($j==($max_cols-1)) {
                echo "<td id='" . $code . "' style='background-color: #FFE4E1;color:green; font-size:10px;'>" . $template . "</td>\n";
            }
            continue;
        }

        $obj = $history[$date][$code];
        // 注意j在前（按列遍历）
        if ($j==($max_cols-1)) {
            echo "<td style='background-color: #FFE4E1;'>" . formatStock($obj, $date) . "</td>\n";
            echo "<td id='" . (string)($obj['code']) . "' style='background-color: #FFE4E1;color:green; font-size:10px;'>" . $template . "</td>\n";
        } else {
            echo "<td style='background-color: #e2e2e2;'>" . formatStock($obj, $date) . "</td>\n";
        }
    }
    echo "</tr>\n";
}
echo "</table>\n";
?>

<script>
  var allStocks = JSON.parse('<?php echo json_encode($codes); ?>');
  var allStocksPriceMap = new Map();
  allStocks.forEach(function(item) {
    allStocksPriceMap[item] = new Array();
  })

  function clearReconnectState() {
    console.log('this.timer ' + this.timer);//我是定时执行
    if (this.timer) {
      console.log('清除重连');//我是定时执行
      clearTimeout(this.timer);
      this.timer = undefined;
    }
    this.connecting = false;
  }

  function getStockUrl(code) {
    if (code.startsWith("60") || code.startsWith("900")) {
        return "href='http://quote.eastmoney.com/sh" + code + ".html'";
    } else if (code.startsWith("688")) {
        return "href='http://quote.eastmoney.com/kcb/" + code + ".html'";
    } else {
        return "href='http://quote.eastmoney.com/sz" + code + ".html'";
    }
  }

  function conWebSocket() {
      if (this.connecting) {
        console.log("connecting...");
        return;
      }

      let vm = this;
      if (window.WebSocket) {
        let ws_url = "ws://39.99.248.27:8888";
        console.log("server: " + ws_url);
        vm.socket = new WebSocket(ws_url);
        let socket = vm.socket;

        vm.connecting = true;

        socket.onopen = function (e) {
          console.log("连接服务器成功");

          vm.clearReconnectState();
        };
        socket.onclose = function (e) {
          console.log("连接服务器失败");

          vm.clearReconnectState();
          vm.timer = setTimeout(function () {
            console.log('重连');//我是定时执行
            conWebSocket();
          }, 5000);
        };
        socket.onerror = function () {
          clearReconnectState();
          console.log("onerror");
        };
        // 接收服务器的消息
        socket.onmessage = function (e) {
          let msg = JSON.parse(e.data);
          console.log("收到消息: " + msg.type);
          if (msg.type == 'handshake') {
            let sub = {};
            sub.type = 'observe';
            sub.stocks = allStocks;
            socket.send(JSON.stringify(sub));
            console.log("oserve stocks: " + allStocks);
            return;
          }

          if (msg.type == 'flow') {
            let idx = 0;
            msg.data.forEach(function (item) {
              let sufix = "rank_" + idx + "_";
              document.getElementById(sufix+"up").innerHTML = item.up + "%";
              document.getElementById(sufix+"name").innerHTML = "<a " + getStockUrl(item.code) + " target='_blank'>" + item.name + "-" + item.code + "</a>";
              document.getElementById(sufix+"price").innerHTML = item.price;
              document.getElementById(sufix+"up").innerHTML = item.up + "%";
              document.getElementById(sufix+"mbig").innerHTML = "净额: " + item.mbig + "<p style='margin:0px;padding:0px;'>占比: " + item.mbig_p + "%</p>";
              document.getElementById(sufix+"sbig").innerHTML = "净额: " + item.sbig + "<p style='margin:0px;padding:0px;'>占比: " + item.sbig_p + "%</p>";

              if (item.up > 0) {
                document.getElementById(sufix+"up").style = 'font-size:10px;color:red';
              } else if (item.up < 0) {
                document.getElementById(sufix+"up").style = 'font-size:10px;color:green';
              } else {
                document.getElementById(sufix+"up").style = 'font-size:10px;color:black';
              }

              idx++;
            })
            return;
          }

          total_up = 0;
          count = 0;
          if (msg.type == 'notity') {
            msg.data.forEach(function (item) {
              if (typeof(allStocksPriceMap[item.code]) == "undefined") {
                return
              }
              allStocksPriceMap[item.code].push(item.price);
              content = "<br/>时间: " + item.time;
              content += "<br/>价格: " + item.price;
              content += "<br/>昨收: " + item.close;
              content += "<br/>量比: " + item.qrr;
              content += "<br/>涨跌幅: " + item.up + "%";
              content += "<br/>成交量: " + item.volume;
              content += "<br/>超大单流入: " + item.sbig;
              content += "<br/>主力净流入: " + item.mbig;
              if (document.getElementById(item.code) == null) {
                console.log("no observe " + item.code);
                return
              }
              total_up += parseFloat(item.up);
              count++;
              if (item.up > 0) {
                document.getElementById(item.code).style = 'background-color: #FFE4E1;color:red; font-size:10px';
              } else if (item.up < 0) {
                document.getElementById(item.code).style = 'background-color: #FFE4E1;color:green; font-size:10px';
              } else {
                document.getElementById(item.code).style = 'background-color: #FFE4E1;color:black; font-size:10px';
              }
              document.getElementById(item.code).innerHTML = content;
            })

            total_up /= count;
            if (total_up > 0) {
                document.getElementById('realtime').style = 'color:red';
            } else {
                document.getElementById('realtime').style = 'color:green';
            }
            document.getElementById('realtime').innerHTML = "实时 " + total_up.toFixed(2) + "%";
          }
        };
      }
    }

    conWebSocket();
</script>

</body>
</html>
